package com.example.controller;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.domain.User;
import com.example.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
public class LoginController {

    @Autowired
    private UserService userService;

    @Operation(summary = "登录接口", description = "用于用户登录")
    @PostMapping("/login")
    public SaResult login(String username, String password) {
        // SHA1密码加密
        String processedPassword = SaSecureUtil.sha1(password);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        queryWrapper.eq("password", processedPassword);
        User user = userService.getOne(queryWrapper);
        if (user != null) {
            StpUtil.login(user.getId());
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            return SaResult.ok("登录成功").setData(tokenInfo);
        }
        return SaResult.error("用户名或密码错误");
    }

    @Operation(summary = "注销接口", description = "用于用户注销登录")
    @GetMapping("/logout")
    public SaResult logout() {
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        log.info("用户注销登录: {}", tokenInfo);
        StpUtil.logout();
        return SaResult.ok("注销成功");
    }
}
